<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "password"
});
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { changePassword, type ChangePasswordResponse } from "@/api/password";
import { send } from "@/api/user";
import { useUserStoreHook } from "@/store/modules/user";

// 手机号正则
const REGEXP_PHONE = /^1[1-9]\d{9}$/;

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive({
  contact_phone: "",
  captcha: "",
  new_password: "",
  confirm_password: ""
});

// 表单验证规则
const formRules = reactive<FormRules>({
  contact_phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      pattern: REGEXP_PHONE,
      message: "请输入正确的手机号格式",
      trigger: "blur"
    }
  ],
  captcha: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur"
    }
  ],
  new_password: [
    {
      required: true,
      message: "请输入新密码",
      trigger: "blur"
    },
    {
      min: 6,
      message: "新密码长度不能少于6位",
      trigger: "blur"
    }
  ],
  confirm_password: [
    {
      required: true,
      message: "请确认新密码",
      trigger: "blur"
    }
  ]
});

const submitting = ref(false);

// 发送验证码倒计时
const countdown = ref(0);
const canSendCode = ref(true);

// 发送验证码
const sendVerifyCode = async () => {
  if (!form.contact_phone) {
    ElMessage.warning("请先输入手机号");
    return;
  }

  // 验证手机号格式
  if (!REGEXP_PHONE.test(form.contact_phone)) {
    ElMessage.warning("请输入正确的手机号格式");
    return;
  }

  try {
    // 调用发送短信验证码接口
    const res: any = await send({
      mobile: form.contact_phone,
      event: "changepwd"
    });

    if (res.success || res.code === 1) {
      ElMessage.success("验证码发送成功");
      // 开始倒计时
      countdown.value = 60;
      canSendCode.value = false;

      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
          canSendCode.value = true;
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg || "验证码发送失败");
    }
  } catch (error) {
    ElMessage.error("验证码发送失败");
    console.error("发送验证码错误:", error);
  }
};

// 确认修改密码
const handleConfirm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      // 验证新密码和确认密码是否一致
      if (form.new_password !== form.confirm_password) {
        ElMessage.error("两次输入的密码不一致");
        return;
      }

      try {
        submitting.value = true;
        const payload = {
          contact_phone: form.contact_phone,
          new_password: form.new_password,
          captcha: form.captcha
        };

        const res: ChangePasswordResponse & { success?: boolean } =
          await changePassword(payload);
        const success = res?.success === true || res?.code === 1;

        if (success) {
          ElMessage.success(res.msg || "密码修改成功，请重新登录");
          // 重置表单
          form.contact_phone = "";
          form.captcha = "";
          form.new_password = "";
          form.confirm_password = "";
          // 退出登录
          useUserStoreHook().logOut();
        } else {
          ElMessage.error(res?.msg || "密码修改失败，请重试");
        }
      } catch (error) {
        console.error("修改密码失败:", error);
        ElMessage.error("修改密码失败，请稍后重试");
      } finally {
        submitting.value = false;
      }
    }
  });
};
</script>

<template>
  <div class="password-container">
    <div class="password-header">
      <div class="title-up">A1111</div>
      <div class="title-down">中国国际核工业展览会</div>
    </div>
    <div class="password-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="150px"
        size="large"
      >
        <el-form-item label="手机号:" prop="contact_phone">
          <div class="phone-input-container">
            <el-input
              v-model="form.contact_phone"
              placeholder="请输入手机号"
              style="width: 300px; margin-right: 10px"
            />
            <el-button
              size="large"
              :disabled="!canSendCode"
              style="width: 140px; min-width: 140px"
              @click="sendVerifyCode"
            >
              {{ canSendCode ? "发送验证码" : `${countdown}s` }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="验证码:" prop="captcha">
          <el-input
            v-model="form.captcha"
            placeholder="请输入验证码"
            style="width: 450px"
          />
        </el-form-item>

        <el-form-item label="新密码:" prop="new_password">
          <el-input
            v-model="form.new_password"
            type="password"
            placeholder="请输入新密码"
            show-password
            style="width: 450px"
          />
        </el-form-item>

        <el-form-item label="确认密码:" prop="confirm_password">
          <el-input
            v-model="form.confirm_password"
            type="password"
            placeholder="请确认新密码"
            show-password
            style="width: 450px"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="confirm-button">
      <el-button
        type="primary"
        size="large"
        round
        style="width: 100px; margin-top: 20px; background-color: #17a2b8"
        :loading="submitting"
        :disabled="submitting"
        @click="handleConfirm"
      >
        确认修改
      </el-button>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.password-container {
  width: 96%;
  height: 100%;
  background-color: #fff;

  .password-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 150px;
    border-bottom: 1px solid #ccc;

    .title-up {
      font-size: 30px;
      font-weight: bold;
    }

    .title-down {
      font-size: 20px;
    }
  }

  .password-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 96%;
    padding-top: 50px;

    .phone-input-container {
      display: flex;
      align-items: center;
    }

    :deep(.el-form-item) {
      margin-bottom: 20px;

      .el-form-item__label {
        font-weight: 500;
        color: #333;
      }

      .el-input__wrapper {
        border-radius: 4px;
      }
    }
  }

  .confirm-button {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-top: 30px;
  }
}
</style>
